<?php

$user = $_POST['user'];
$type = $_POST['type'];
$timestamp = $_POST['timestamp'];
$status = $_POST['status'];


//finding the other user
$arr = explode("_",$type);
$u1 = $arr[1];
$u2 = $arr[2];

if($user == $u1)
	$u = $u2;
else 
	$u = $u1;

date_default_timezone_set('Asia/Calcutta');
$flag = 0;
$doc = new DOMDocument();
$response = array();
$response['output'] = "";

$new_avail = 0;
$status_new = "";

//for($i=0;$i<3;$i++)
//{
	//usleep(2000000); // sleep for two seconds
  $filename1 = '../../../chat/'.$type.'.xml';
  $filename2 = '../../../chat/'.$type.'_'.$u.'.xml';
  

 		 $counter = 0;  
		  while($flag == 0 && $counter<40)
		  {
		  
				$fhandle1 = fopen($filename1, "r");
				if($fhandle1) {
				$contents = fread($fhandle1, filesize($filename1));
				$timestampins = $contents;
					//$response["output"].=$timestampins." ";
				if((int)$timestampins > (int)$timestamp)
				 { $flag = 1; $new_avail = 1; break; }
				}
				//for checking if the user is typing
				//open the file,  if not able to open then ignore
				
				$fhandle2 = fopen($filename2, "r");				
				if($fhandle2) {
				$contents = fread($fhandle2, filesize($filename2));
				if($contents != $status) { 
					$status_new = $contents;
					$flag = 1; 
				 }
				}
			
			if($flag == 1) break;
			
		 // sleep for one second	  	
			$counter++;
			usleep(500000);		
	 	 }  	
  
  		fclose($fhandle1);
		fclose($fhandle2);
	

	 $time = time(); 
	 
	 
	$response["status"] = $status_new;
	$response["time"] = $time;

	if($new_avail==1)
		$response["new"] = "true";	
	else if($new_avail!=1)
		$response["new"] = "false";		

echo json_encode($response);
 
?>